package com.zero.qth.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zero.common.core.domain.page.PageDomain;
import com.zero.common.core.exception.ServiceException;
import com.zero.qth.controller.req.CouponUserBatchAddReq;
import com.zero.qth.domain.Coupon;
import com.zero.qth.service.ICouponService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zero.common.annotation.log.Log;
import com.zero.common.core.basecontroller.BaseController;
import com.zero.common.core.domain.result.AjaxResult;
import com.zero.common.core.enums.BusinessType;
import com.zero.qth.domain.CouponUser;
import com.zero.qth.service.ICouponUserService;
import com.zero.common.core.utils.poi.ExcelUtil;
import com.zero.common.core.domain.page.TableDataInfo;

/**
 * 优惠券-用户-列表Controller
 * 
 * @author cai-xu-kun
 * @date 2025-08-27
 */
@RestController
@RequiredArgsConstructor
@Api(tags = "优惠券-用户-列表")
@RequestMapping("/qth/couponUser")
public class CouponUserController extends BaseController {

    private final ICouponUserService couponUserService;

    private final ICouponService couponService;

    @ApiOperation("发放优惠券批量插入用户")
    @PreAuthorize("@ss.hasPermi('qth:couponUser:add')")
    @PostMapping("/batchAdd")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult batchAdd(@RequestBody CouponUserBatchAddReq req) {
        if (req.getUserIds().isEmpty()) {
            throw new ServiceException("参数错误");
        }
        // 检查优惠券剩余数量 1.查询剩余数量 2.如果发放 > 剩余，抛出异常 3.剩余-发出，更新字段
        Coupon coupon = couponService.getById(req.getCouponId());
        if (coupon == null) {
            throw new ServiceException("参数错误");
        } else if (coupon.getRemainingQuantity() < req.getUserIds().size()) {
            throw new ServiceException("剩余优惠券数量不足");
        }
        coupon.setRemainingQuantity(coupon.getRemainingQuantity() - req.getUserIds().size());
        couponService.updateById(coupon);

        // 发放优惠券
        ArrayList<CouponUser> couponUsers = new ArrayList<>();
        for (Long userId : req.getUserIds()) {
            CouponUser couponUser = new CouponUser();
            couponUser.setUserId(userId);
            couponUser.setCouponId(req.getCouponId());
            couponUsers.add(couponUser);
        }
        couponUserService.saveBatch(couponUsers);

        return toAjax(couponUsers.size());
    }
/*=============================================================================*/
    /**
     * 查询优惠券-用户-列表分页
     */
    @ApiOperation("查询优惠券-用户-列表分页")
    @PreAuthorize("@ss.hasPermi('qth:couponUser:list')")
    @GetMapping("/list")
    public TableDataInfo list(CouponUser couponUser) {
        PageDomain pageDomain = this.startPage();
        Page<CouponUser> p = new Page<>(pageDomain.getPageNum(), pageDomain.getPageSize());
        Page<CouponUser> page = couponUserService.selectCouponUserListPage(couponUser, p);
        return this.getDataTable(page);
    }

    /**
     * 导出优惠券-用户-列表列表
     */
    @ApiOperation("导出优惠券-用户-列表列表")
    @PreAuthorize("@ss.hasPermi('qth:couponUser:export')")
    @Log(title = "优惠券-用户-列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CouponUser couponUser) {
        List<CouponUser> list = couponUserService.selectCouponUserList(couponUser);
        ExcelUtil<CouponUser> util = new ExcelUtil<CouponUser>(CouponUser.class);
        util.exportExcel(response, list, "优惠券-用户-列表数据");
    }

    /**
     * 获取优惠券-用户-列表详细信息
     */
    @ApiOperation("获取优惠券-用户-列表详细信息")
    @PreAuthorize("@ss.hasPermi('qth:couponUser:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(couponUserService.selectCouponUserById(id));
    }

    /**
     * 新增优惠券-用户-列表
     */
    @ApiOperation("新增优惠券-用户-列表")
    @PreAuthorize("@ss.hasPermi('qth:couponUser:add')")
    @Log(title = "优惠券-用户-列表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CouponUser couponUser) {
        return toAjax(couponUserService.insertCouponUser(couponUser));
    }

    /**
     * 修改优惠券-用户-列表
     */
    @ApiOperation("修改优惠券-用户-列表")
    @PreAuthorize("@ss.hasPermi('qth:couponUser:edit')")
    @Log(title = "优惠券-用户-列表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CouponUser couponUser) {
        return toAjax(couponUserService.updateCouponUser(couponUser));
    }

    /**
     * 删除优惠券-用户-列表
     */
    @ApiOperation("删除优惠券-用户-列表")
    @PreAuthorize("@ss.hasPermi('qth:couponUser:remove')")
    @Log(title = "优惠券-用户-列表", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(couponUserService.deleteCouponUserByIds(ids));
    }
}
